package com.rams.jhms.gui.datamodels;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import com.rams.jhms.dao.DerbySettingsFSFoldersDAO;
import com.rams.jhms.dto.FSPropsFolderDTO;
import com.rams.jhms.dto.MediaFile;
import com.rams.jhms.fs.FSFolder;

public class FSTreeModel implements TreeModel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8764826372409143212L;
	
	protected String root;
	protected List<FSPropsFolderDTO> subroots = new ArrayList<FSPropsFolderDTO>();
	protected ArrayList<FSFolder> roots = new ArrayList<FSFolder>();
	
	public FSTreeModel() {
		root = "jHomeMediaPaths";

		getSubRoots();
		
		for (FSPropsFolderDTO path : subroots) {
			File f = new File(path.getPath());
			if (f.exists()) {
				roots.add(new FSFolder(f));
			}
		}
	}
	
	private void getSubRoots() {
		DerbySettingsFSFoldersDAO dao = new DerbySettingsFSFoldersDAO();
		subroots = dao.getFolders();
	}
	
	public Object getChild(Object parent, int index) {
		if (parent.equals(root)) {
			return roots.get(index);
		}
		
	    return ((FSFolder)parent).getChild(index);
	}

	public int getChildCount(Object parent) {
		if (parent.equals(root)) {
			return roots.size();
		}

	    return ((FSFolder)parent).getChildCount();
	}

	public int getIndexOfChild(Object parent, Object child) {
		if (parent.equals(root)) {
			for (int i = 0; i < roots.size(); i++) {
				if (roots.get(i).equals(child))
					return i;
			}
			return -1;
		}
		
		String[] children = ((MediaFile)parent).list();
	    if (children == null) 
	    	return -1;
	    String childname = ((MediaFile)child).getName();
	    for(int i = 0; i < children.length; i++) {
	      if (childname.equals(children[i])) 
	    	  return i;
	    }
	    return -1;
	}

	public Object getRoot() {
		return root;
	}

	public boolean isLeaf(Object node) {
		if (node.equals(root)) {
			if (roots.size() > 0) {
				return false;
			} else {
				return true;
			}
		}
		return ((FSFolder)node).getChildCount() == 0; 
	}
	
	public void valueForPathChanged(TreePath path, Object newValue) { }
	public void addTreeModelListener(TreeModelListener l) {	}
	public void removeTreeModelListener(TreeModelListener l) { }
}
